package com.fcscs.cservice.service.impl;

import org.hibernate.event.PostInsertEvent;
import org.hibernate.event.PostInsertEventListener;
import org.hibernate.event.PostUpdateEvent;
import org.hibernate.event.PostUpdateEventListener;

import com.fcscs.core.system.ApplicationContextHolder;
import com.fcscs.cservice.common.CServiceCommonEnums.UpdateVerLevelEnum;
import com.fcscs.cservice.domain.VersionUpdates;
import com.fcscs.cservice.domain.VersionableEntity;
import com.fcscs.cservice.service.ECMSVersionManager;

public class VersionableEventListener implements  PostUpdateEventListener, PostInsertEventListener {
	private static final long serialVersionUID = 8560398224509958386L;

	public void deleteVersionalbeEntity(VersionableEntity entity) {
		ECMSVersionManager vMgr = (ECMSVersionManager)ApplicationContextHolder.getBeanFromContext("ecmsVersionManager");
		vMgr.updateVersionValues(entity.getOrgId(), entity.getPropertyId(), entity.getModuleEnum(), entity.getEntityTypeEnum(), entity.getEntityId(), UpdateVerLevelEnum.ENT_TYPE);
	}
	
	public void insertVersionalbeEntity(VersionableEntity entity) {
		ECMSVersionManager vMgr = (ECMSVersionManager)ApplicationContextHolder.getBeanFromContext("ecmsVersionManager");
		vMgr.updateVersionValues(entity.getOrgId(), entity.getPropertyId(), entity.getModuleEnum(), entity.getEntityTypeEnum(), entity.getEntityId(), UpdateVerLevelEnum.ENT_TYPE);
	}
	
	public void updateVersionalbeEntity(VersionableEntity entity) {
		ECMSVersionManager vMgr = (ECMSVersionManager)ApplicationContextHolder.getBeanFromContext("ecmsVersionManager");
		vMgr.updateVersionValues(entity.getOrgId(), entity.getPropertyId(), entity.getModuleEnum(), entity.getEntityTypeEnum(), entity.getEntityId(), UpdateVerLevelEnum.ENT);
	}

	@SuppressWarnings("unused")
	private static VersionUpdates getModuleUpdateObj(VersionableEntity entity) {
		VersionUpdates vv = new VersionUpdates();
		vv.setOrgId(entity.getOrgId());
		vv.setPropertyId(entity.getPropertyId());
		vv.setModuleEnum(entity.getModuleEnum());
		return vv;
	}

	public void onPostDelete(VersionableEntity entity) {
		deleteVersionalbeEntity(entity);
	}

	public void onPostInsert(PostInsertEvent event) {
		if (event.getEntity() instanceof VersionableEntity) {
			insertVersionalbeEntity((VersionableEntity)event.getEntity());
		}
	}

	public void onPostUpdate(PostUpdateEvent event) {
		if (event.getEntity() instanceof VersionableEntity) {
			updateVersionalbeEntity((VersionableEntity)event.getEntity());
		}
	}
}
